package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.utils.HtmlCleaner;
import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;

public class YuanlinNewsAnalyse implements AnalyseNews{
		private static final String[] regex={
					"http://[a-z]*.yuanlin.com/detail/[0-9]*/[0-9]*.htm",
					"http://[a-z]*.yuanlin.com/infodetail/[0-9]*.htm",
					"http://[a-z]*.yuanlin.com/[a-z]*/[a-z]*/[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}/[0-9]*.html",
		};
		
		public boolean isDetailPage(String url) {
			for (int i=0; i < regex.length; i++) {
				if (url.matches(regex[i])) {
					return true;
				}
			}
			return false;
		}

		
		public NewsMeta Update(NewsMeta meta) {
			return null;
		}

		
		public NewsMeta parserHtml(UrlMeta urlMeta) {
			NewsMeta news=new NewsMeta();
			if (urlMeta.getHtml() == null) {
			}
			String htmltxt=urlMeta.getHtml();
			String url=urlMeta.getUrl();


			String title=null;
			String content=null;
			String author=null;
			Long date=null;
			Document doc=Jsoup.parse(htmltxt);
			title=doc.select("div#ArticleTit").text();
			if(StringUtils.isBlank(title)){
				title=doc.select("h1").text();
				if(StringUtils.isBlank(title)){
					title=doc.select("td.style5").text();
				}
			}
			content=HtmlCleaner.getContentHtml(url,doc.select("div#ArticleCnt"));
			if(StringUtils.isBlank(content)){
				content=HtmlCleaner.getContentHtml(url,doc.select("div.article div p"));
				if(StringUtils.isBlank(content)){
					content=HtmlCleaner.getContentHtml(url,doc.select("td.style6"));
				}
			}

			author=JSoupUtils.matchAuthor(doc, "来源:");

			date=DateUtils.matchDate(doc.select("div#ArtFrom").text());
			if(date == null){
				date=DateUtils.matchDate(doc.select("div.article h2").text());
				if(date == null){
					date=DateUtils.matchDate(doc.select("td.style3").text());
				}
			}
			news.setUrl(url);
			news.setTitle(title);
			news.setContent(content);
			news.setAuthor(author);
			news.setDate(date);
			return news;
		}

		public static void main(String[] args) {
			YuanlinNewsAnalyse test=new YuanlinNewsAnalyse();

			String url="http://www.cnzicai.com/news/detail/20140704/188141.html";
			System.out.println(test.isDetailPage(url));
			UrlMeta meta=CrawlHTML.responseToURL(url);
			NewsMeta parserHtml=test.parserHtml(meta);
			System.out.println(parserHtml);
		}
		
		public boolean isNeedUpdate(){
			return false;
		}
}
